import { memo, useEffect, useRef, useState } from "react";
import { OrderType } from "../../../../types/order";
import { Card } from "antd";
import * as echarts from "echarts";
import { useAsyncEffect } from "ahooks";
import { useGetStudentInfo_simple } from "../../../../service/student";

const SpendRank = memo(({ orders }: { orders: OrderType[] }) => {
  const chartRef = useRef(null);
  const { getStudentInfo, loading } = useGetStudentInfo_simple();
  const showStudentNum = 5;
  const [spendMap, setSpendMap] = useState<Map<string, number>>(new Map());
  const [students, setStudents] = useState<Map<string, string>>(new Map());
  useEffect(() => {
    if (orders && orders.length > 0) {
      const allStudentSpand: typeof spendMap = new Map();
      // 进入排行榜单的数据
      const data: typeof spendMap = new Map();
      let currentMinSpendUser = { id: "0", spend: Infinity };
      for (const order of orders) {
        if (allStudentSpand.has(order.userId)) {
          allStudentSpand.set(order.userId, allStudentSpand.get(order.userId)! + Number(order.buyPrice));
        } else {
          allStudentSpand.set(order.userId, Number(order.buyPrice));
        }
        const currentUserSpend = allStudentSpand.get(order.userId) ?? 0;
        // 达到最大允许展示条数
        if (data.size === showStudentNum) {
          // 替换掉花费最小的用户
          if (currentUserSpend > currentMinSpendUser.spend) {
            data.delete(currentMinSpendUser.id);
            data.set(order.userId, currentUserSpend);
            // 重新计算最小花费的用户
            const min: typeof currentMinSpendUser = { id: order.userId, spend: currentUserSpend };
            // 此处翻转的原因为：如果不同用户存在一样的消费那么保留优先付款的用户
            Array.from(data.keys()).reverse().forEach(item => {
              if (data.get(item) ?? 0 < min.spend) {
                min.id = item;
                min.spend = data.get(item) ?? 0;
              }
            });
            currentMinSpendUser = min;
          }
        } else {
          data.set(order.userId, currentUserSpend);
          // 重新计算最小花费的用户
          if (currentUserSpend <= currentMinSpendUser.spend) {
            currentMinSpendUser = { id: order.userId, spend: currentUserSpend };
          }
        }
      }
      setSpendMap(data);
    }
  }, [orders]);
  useAsyncEffect(async () => {
    // 获取学员数据
    if (spendMap.size > 0) {
      const stus: typeof students = new Map();
      for (const id of Array.from(spendMap.keys())) {
        const res = await getStudentInfo(id);
        stus.set(id, res.name === "" ? "淡云教育用户" + id : res.name);
      }
      setStudents(stus);
    }
  }, [spendMap]);
  useEffect(() => {
    const option = {
      graphic: {
        type: "text",
        left: "center",
        top: "middle",
        style: {
          text: orders.length === 0 ? "暂无学员" : "",
          fontSize: 20,
          fontWeight: "bold",
          fill: "#aaa"
        }
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow"
        },
        textStyle: {
          color: "#fff",
          align: "left",
          fontSize: 14
        },
        backgroundColor: "rgba(0,0,0,0.8)"
      },
      xAxis: {
        type: "value",
        name: "元",
        nameTextStyle: {
          color: "#838383"
        }
      },
      yAxis: {
        type: "category",
        data: Array.from(students.values()),
        inverse: true,
        animationDuration: 300,
        animationDurationUpdate: 300
      },
      series: [
        {
          realtimeSort: true,
          name: "学员消费排行",
          type: "bar",
          data: Array.from(spendMap.values()),
          label: {
            show: true,
            position: "right",
            valueAnimation: true
          },
          itemStyle: {
            color: "#5fc5ee",
            borderRadius: [0, 15, 15, 0]
          }
        }
      ],
      legend: {
        show: true
      }
    };
    const chartInstance = echarts.init(chartRef.current);
    chartInstance.setOption(option);
  }, [spendMap, students]);
  return (
    <Card title="消费排行" bordered={false} style={{ width: "100%" }} loading={loading}>
      <div ref={chartRef} style={{ width: "100%", height: "30vh" }}></div>
    </Card>
  );
});

export default SpendRank;
